angular.module('starter.services', [])

  .factory('UserFactory', function(ENV,$resource,$ionicPopup,$rootScope,$state,DpDataBase) {
    var APIUrl = ENV.api;
    var resource_employer_register=APIUrl+'api/user/register';
    var resource_employer_login=APIUrl+'api/user/login';
    var resource_employee_register=APIUrl+'user/register';
    var resource_employee_login=APIUrl+'employee/doEmployeeLogin';
    var resource_all_roles=APIUrl+'api/role/get_all_role_data';
    var resource_employee_roleid=APIUrl+'employee/api/productList';
    var resource_employee_info_id=APIUrl+'employee/doGetEmploye';
    var resource_dogetrank=APIUrl+'employee/dogetrank';
    var resource_add_order=APIUrl+'api/order/addOrder';
    var resource_role_id=APIUrl+'api/role/getRoleInfo';
    var resourxe_edit_password=APIUrl+'api/user/reset_password';
    var resourxe_sign_up=APIUrl+'wap/user/doEmployeeRegister';
    var resourxe_order_list=APIUrl+'api/order/getOrdersbyCondition';
    var resourxe_order_list2=APIUrl+'api/order/getEmpOrdersbyCondition';
    var resource_order_detail=APIUrl+'api/order/orderInfo2';
    var resource_get_info=APIUrl+'api/user/get_info';
    var resource_edit_info=APIUrl+'api/user/update';
    var resource_update_order=APIUrl+'api/order/updateOrder';
    var resource_forget_employee=APIUrl+'employee/frogetPassword';
    var resource_forget_employer=APIUrl+'api/user/frogetPassword';
    var resource_employer_comment=APIUrl+'wap/comment/doGetBossComment';
    var resource_employee_comment=APIUrl+'wap/comment/doGetComment';

    var roleList,employeeList,employeeInfo,trankList,roleInfo,orderList,orderList2,employerInfo,orderDetail,employerComment,employeeComment;

    var resource_order=$resource(APIUrl+'deliver/get_order/v1',
      {token:"@token"},
      {save:{
        method:'post',
        timeout:ENV.delayTime}
      });
    var resource_un_reach_order=$resource(APIUrl+'deliver/get_un_reach_order/v1',
      {token:"@token"},
      {save:{
        method:'post',
        timeout:ENV.delayTime}
      });
    var resource_reach_order=$resource(APIUrl+'deliver/get_reach_order/v1',
      {token:"@token"},
      {save:{
        method:'post',
        timeout:ENV.delayTime}
      });
    var resource_sign_order=$resource(APIUrl+'deliver/sign_order/v1',
      {token:"@token"},
      {save:{
        method:'post',
        timeout:ENV.delayTime}
      });
    var resource_deliver_info=$resource(APIUrl+'deliver/get_deliver_info/v1',
      {token:"@token"},
      {save:{
        method:'post',
        timeout:ENV.delayTime}
      });
    var resource_refuse_sign_order=$resource(APIUrl+'deliver/refuse_sign_order/v1',
      {token:"@token"},
      {save:{
        method:'post',
        timeout:ENV.delayTime}
      });

    return{
      getEmployeeComment: function (id) {
        $.ajax({
          type:"post",
          url:resource_employee_comment,
          data:{employeeId:id},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            if(obj.rs){
              employeeComment=obj.datas;
              $rootScope.$broadcast('getEmployeeComment');
            }else{
              layer.msg(obj.msg);
            }
          },
          error: function (obj) {
            console.log(obj);
          }
        });
      },
      returnEmployeeComment: function () {
        return employeeComment;
      },
      getEmployerComment: function () {
        $.ajax({
          type:"post",
          url:resource_employer_comment,
          data:{bossId:ENV.userId},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            if(obj.rs){
              employerComment=obj.datas;
              $rootScope.$broadcast('getEmployerComment');
            }else{
              layer.msg(obj.msg);
            }
          },
          error: function (obj) {
            console.log(obj);
          }
        });
      },
      returnEmployerComment: function () {
        return employerComment;
      },
      forgetEmployer: function (phone) {
        $.ajax({
          type:"post",
          url:resource_forget_employer,
          data:{phone:phone},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            if(obj.rs){
              layer.msg("发送成功",function () {
                $state.go("tab.setting");
              });
            }else{
              layer.msg(obj.msg);
            }
          },
          error: function (obj) {
            console.log(obj);
          }
        });
      },
      forgetEmployee: function (phone) {
        $.ajax({
          type:"post",
          url:resource_forget_employee,
          data:{phone:phone},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            if(obj.rs){
              //$rootScope.$broadcast("editEmployerInfoServer");
              layer.msg("发送成功",function () {
                $state.go("tab.setting");
              });
            }else{
              layer.msg(obj.msg);
            }
          },
          error: function (obj) {
            console.log(obj);
          }
        });
      },
      changeOrderState: function (id,type,status) {
        $.ajax({
          type:"post",
          url:resource_update_order,
          data:{id:id,updateType:1,reasonType:type,status:status},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            if(obj.rs){
              //$rootScope.$broadcast("editEmployerInfoServer");
              //layer.msg("修改成功",function () {
              //  ENV.userName=info.username;
              //  $state.go("tab.setting");
              //});
            }else{
              layer.msg(obj.msg);
            }
          },
          error: function (obj) {
            console.log(obj);
          }
        });
      },
      editEmployerInfoServer: function (info) {
        $.ajax({
          type:"post",
          url:resource_edit_info,
          data:{id:info.userId,username:info.username,email:info.email,sex:info.sex,address:info.address},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            if(obj.rs){
              //$rootScope.$broadcast("editEmployerInfoServer");
              layer.msg("修改成功",function () {
                ENV.userName=info.username;
                $state.go("tab.setting");
              });
            }else{
              layer.msg(obj.msg);
            }
          },
          error: function (obj) {
            console.log(obj);
          }
        });
      },
      getEmployerInfoServer: function (userId) {
        //alert(userId);
        $.ajax({
          type:"post",
          url:resource_get_info,
          data:{id:userId},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            if(obj.rs){
              employerInfo=obj.datas;
              $rootScope.$broadcast("getEmployerInfoServer");
            }else{
              layer.msg(obj.msg);
            }
          },
          error: function (obj) {
            console.log(obj);
          }
        });
      },
      returnEmployerInfo: function () {
        return employerInfo;
      },
      getOrderList: function () {
        $.ajax({
          type:"post",
          url:resourxe_order_list,
          data:{userId:ENV.userId,pageNo:1,pageSize:100},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            if(obj.rs){
              orderList=obj.datas.result;
              $rootScope.$broadcast("getOrderList");
            }else{
              layer.msg(obj.msg);
            }
          },
          error: function (obj) {
            console.log(obj);
          }
        });
      },
      getOrderList2: function () {
        //alert(ENV.userId);
        $.ajax({
          type:"post",
          url:resourxe_order_list2,
          data:{employeeId:ENV.userId,pageNo:1,pageSize:100},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            if(obj.rs){
              orderList2=obj.datas.result;
              $rootScope.$broadcast("getOrderList2");
            }else{
              layer.msg(obj.msg);
            }
          },
          error: function (obj) {
            console.log(obj);
          }
        });
      },
      returnOrder: function () {
        return orderList;
      },
      returnOrder2: function () {
        return orderList2;
      },
      employeeSignUp: function (userInfo) {
        $.ajax({
          type:"post",
          url:resourxe_sign_up,
          data:{id:userInfo.id},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            //if(obj.rs){
            //  layer.msg(obj.msg,function () {
            //    history.go(-1);
            //  });
            //}else{
            //  layer.msg(obj.msg);
            //}
          },
          error: function (obj) {
            console.log(obj);
          },
          beforeSend:function(){
            loadIndex = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
          },
          complete:function(){
            layer.close(loadIndex);
          }
        });
      },
      editPassword: function (userInfo) {
        $.ajax({
          type:"post",
          url:resourxe_edit_password,
          data:{id:userInfo.id,password:userInfo.password,new_password:userInfo.password2},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            if(obj.rs){
              layer.msg(obj.msg,function () {
                history.go(-1);
              });
            }else{
              layer.msg(obj.msg);
            }
          },
          error: function (obj) {
            console.log(obj);
          },
          beforeSend:function(){
            loadIndex = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
          },
          complete:function(){
            layer.close(loadIndex);
          }
        });
      },
      getRoleInfoServer: function (roleId) {
        //alert(roleId);
        $.ajax({
          type:"post",
          url:resource_role_id,
          data:{roleId:roleId},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            roleInfo=obj.datas;
            $rootScope.$broadcast("getRoleInfoServer");
          },
          error: function (obj) {
            console.log(obj);
          },
          beforeSend:function(){
            loadIndex = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
          },
          complete:function(){
            layer.close(loadIndex);
          }
        });
      },
      returnRoleInfo: function () {
        return roleInfo;
      },
      addOrderServer: function (orderInfo) {
        //alert(orderInfo.userId);
        $.ajax({
          type:"post",
          url:resource_add_order,
          data:{userId:orderInfo.userId,employeeId:orderInfo.employeeId,roleId:orderInfo.roleId,
                serverdate:orderInfo.serverdate,address:orderInfo.address,orderType:orderInfo.orderType,
                payType:orderInfo.payType,interviewType:orderInfo.interviewType,isAgreeTerms:orderInfo.isAgreeTerms,priceDec:orderInfo.priceDec},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            if(obj.rs){
              layer.msg("订单添加成功",function () {
                $state.go("tab.home");
              });
            }else{
              layer.msg(obj.msg);
            }
            //employeeInfo=obj.datas;
            //$rootScope.$broadcast("getEmployeeInfoByIdServer");
          },
          error: function () {

          },
          beforeSend:function(){
            loadIndex = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
          },
          complete:function(){
            layer.close(loadIndex);
          }
        });
      },
      getEmployeeInfoByIdServer: function (id) {
        $.ajax({
          type:"post",
          url:resource_employee_info_id,
          data:{id:id},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            employeeInfo=obj.datas;
            $rootScope.$broadcast("getEmployeeInfoByIdServer");
          },
          error: function () {

          },
          beforeSend:function(){
            loadIndex = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
          },
          complete:function(){
            layer.close(loadIndex);
          }
        });
      },
      returnEmployeeInfo: function () {
        return employeeInfo;
      },
      getEmployeeByRoleIdServer: function (roleId) {
        $.ajax({
          type:"post",
          url:resource_employee_roleid,
          data:{type:roleId,pageNo:1},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            employeeList=obj.datas;
            $rootScope.$broadcast("getEmployeeByRoleIdServer");
          },
          error: function () {

          },
          beforeSend:function(){
            loadIndex = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
          },
          complete:function(){
            layer.close(loadIndex);
          }
        });
      },
      returnEmployeeListByRoleId: function () {
        return employeeList;
      },
      employerSignUpServer:function(userData){
        $.ajax({
          type:"post",
          url:resource_employer_register,
          data:{username:userData.userName,phoneNo:userData.phone,password:userData.password},
          dataType:"json",
          success:function(obj){
            console.log(obj);
            if(obj.rs){
              layer.msg("注册成功",function () {
              });
            }else{
              layer.msg(obj.msg);
            }
          },
          error:function(obj){
          },
          beforeSend:function(){
            loadIndex = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
          },
          complete:function(){
            layer.close(loadIndex);
          }
        });
      },
      employerLoginServer: function (userData) {
        $.ajax({
          type:"post",
          url:resource_employer_login,
          data:{loginType:0,phoneNo:userData.phone,password:userData.password},
          dataType:"json",
          success:function(obj){
            console.log(obj);
            if(obj.rs){
              layer.msg("登入成功",function () {
                //$rootScope.hideHome = 'show';
                //$rootScope.$apply(function () {
                //  $rootScope.hideHome = 'show';
                //});
                ENV.userPhone=obj.datas.phoneNo;
                ENV.userId=obj.datas.userId;
                ENV.userName=obj.datas.username;
                //$rootScope.$watch('hideHome', function() {
                //  $rootScope.hideHome = '';
                //});
                //alert(ENV.userId);
                ENV.userRole='employer';
                $state.go("tab.home");
              });
            }else{
              layer.msg(obj.msg);
            }
          },
          error:function(obj){
          },
          beforeSend:function(){
            loadIndex = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
          },
          complete:function(){
            layer.close(loadIndex);
          }
        });
      },
      employeeLoginServer: function (userData) {
        //ENV.userPhone=userData.phone;
        //ENV.userId="1";
        //$rootScope.$watch('hideHome', function() {
        //  $rootScope.hideHome = 'hide';
        //});
        //$state.go("tab.order");
        //$state.go("tab.home");
        $.ajax({
          type:"post",
          url:resource_employee_login,
          data:{phoneNo:userData.phone,password:userData.password},
          dataType:"json",
          success:function(obj){
            console.log(obj);
            if(obj.rs){
              layer.msg("登入成功",function () {
                ENV.userPhone=obj.datas.phoneNo;
                ENV.userId=obj.datas.userId;
                ENV.userName=obj.datas.username;
                $rootScope.$watch('hideHome', function() {
                  $rootScope.hideHome = 'hide';
                });
                $state.go("tab.order");
              });
            }else{
              layer.msg(obj.msg);
            }
          },
          error:function(obj){
          },
          beforeSend:function(){
            loadIndex = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
          },
          complete:function(){
            layer.close(loadIndex);
          }
        });
      },
      getAllRoleServer: function () {
        $.ajax({
          type:"post",
          url:resource_all_roles,
          dataType:"json",
          success:function(obj){
            console.log(obj);
            if(obj.rs){
              roleList=obj.datas;
              $rootScope.$broadcast("UserFactory.getAllRoleServer");
            }else{
              layer.msg(obj.msg);
            }
          },
          error:function(obj){
          }
        });
      },
      getTogetrankServer: function () {
        $.ajax({
          type:"post",
          url:resource_dogetrank,
          dataType:"json",
          success:function(obj){
            console.log(obj);
            if(obj.rs){
              trankList=obj.datas;
              $rootScope.$broadcast("UserFactory.getTogetrankServer");
            }else{
              layer.msg(obj.msg);
            }
          },
          error:function(obj){
            console.log(obj);
          }
        });
      },
      returnTrank: function () {
        return trankList;
      },
      returnAllRole: function () {
        return roleList;
      },
      getDeliverInfo: function () {
        resource_deliver_info.save({
          token:ENV.token
        }, function (response) {
          console.log(response);
          if(response.resultCode==0){
            user=response.datas;
            $rootScope.$broadcast("UserFactory.getDeliverInfo");
          }
        });
      },
      returnUser: function () {
        return user;
      },
      refuseSignOrder: function (id,reason) {
        resource_refuse_sign_order.save({
          id:id,
          reason:reason,
          token:ENV.token
        }, function (response) {
          console.log(response);
          if(response.resultCode==0){
            var alertPopup = $ionicPopup.alert({
              title: '提示',
              template: "拒签成功",
              okText:'确定',
              cssClass: 'dp-alert'
            });
            alertPopup.then(function(res) {
              console.log('Thank you for not eating my delicious ice cream cone');
              history.go(-1);
            });
          }
        });
      },
      signOrder: function (id) {
        resource_sign_order.save({
          id:id,
          token:ENV.token
        }, function (response) {
          console.log(response);
          if(response.resultCode==0){
            var alertPopup = $ionicPopup.alert({
              title: '提示',
              template: "签收成功",
              okText:'确定',
              cssClass: 'dp-alert'
            });
            alertPopup.then(function(res) {
              console.log('Thank you for not eating my delicious ice cream cone');
              history.go(-1);
            });
          }
        });
      },
      getOrderDetail: function (id) {
        $.ajax({
          type:"post",
          url:resource_order_detail,
          data:{orderId:id},
          dataType:"json",
          success: function (obj) {
            console.log(obj);
            orderDetail=obj.datas;
            $rootScope.$broadcast('UserFactory.getOrderDetail');
          },
          error: function (obj) {
            console.log(obj);
          },
          beforeSend:function(){
            loadIndex = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
          },
          complete:function(){
            layer.close(loadIndex);
          }
        });
      },
      returnOrderDetai: function () {
        return orderDetail;
      },
      login: function(user) {
        $state.go('tab.home');
       /* resource_login.save({
          account:user.phone,//必填
          password:user.password
        }, function (response) {
          console.log(response);
          $rootScope.$broadcast("UserFactory.login");
          if(response.resultCode==10008||response.resultCode==10009){
            printErrorInfo("密码错误",$ionicPopup);
          }else if(response.resultCode==0){
            ENV.token=response.token;
            DpDataBase.createTable();
            DpDataBase.insertTable(response.token);
            $state.go('tab.home');
          }
        });*/
      },
      getReachOrderList: function (key) {
        resource_reach_order.save({
          key:key,//搜索关键字
          page:1,//必填
          rows:ENV.rows,//必填
          token:ENV.token
        }, function (response) {
          console.log(response);
          if(response.resultCode==10013){
            DpDataBase.delTable();
            printErrorInfoAndReturnLogin("token失效，请重新登入",$ionicPopup);
          }else if(response.resultCode==0){
            if (response.datas.length < ENV.rows) {
              hasNextPage = false;
            }
            orders = {
              'nextPage': 2,
              'hasNextPage': hasNextPage,
              'data': response.datas
            };
            $rootScope.$broadcast('OrderList.OrdersUpdated');
          }
        });
      },
      getMoreReachOrderList: function (key) {
        var nextPage = orders.nextPage;
        var hasNextPage = orders.hasNextPage;
        var portalsData = orders.data;
        resource_reach_order.save({
          key:key,//搜索关键字
          page:nextPage,//必填
          rows:ENV.rows,//必填
          token:ENV.token
        }, function (response) {
          console.log(response);
          if(response.resultCode==10013){
            DpDataBase.delTable();
            printErrorInfoAndReturnLogin("token失效，请重新登入",$ionicPopup);
          }else if(response.resultCode==0){
            nextPage++;
            if (response.datas.length < ENV.rows) {
              hasNextPage = false;
            }
            ordersData = portalsData.concat(response.datas);
            orders = {
              'nextPage': nextPage,
              'hasNextPage': hasNextPage,
              'data': ordersData
            };
            $rootScope.$broadcast('OrderList.OrdersUpdated');
          }
        });
      },
      getUnReachOrderList: function (key) {
        var hasNextPage = true;   //是否有下一页
        resource_un_reach_order.save({
          key:key,//搜索关键字
          page:1,//必填
          rows:ENV.rows,//必填
          token:ENV.token
        }, function (response) {
          console.log(response);
          if(response.resultCode==10013){
            DpDataBase.delTable();
            printErrorInfoAndReturnLogin("token失效，请重新登入",$ionicPopup);
          }else if(response.resultCode==0){
            if (response.datas.length < ENV.rows) {
              hasNextPage = false;
            }
            orders = {
              'nextPage': 2,
              'hasNextPage': hasNextPage,
              'data': response.datas
            };
            $rootScope.$broadcast('OrderList.OrdersUpdated');
          }
        });
      },
      getMoreUnReachOrderList: function (key) {
        var nextPage = orders.nextPage;
        var hasNextPage = orders.hasNextPage;
        var portalsData = orders.data;
        resource_un_reach_order.save({
          key:key,//搜索关键字
          page:nextPage,//必填
          rows:ENV.rows,//必填
          token:ENV.token
        }, function (response) {
          console.log(response);
          if(response.resultCode==10013){
            DpDataBase.delTable();
            printErrorInfoAndReturnLogin("token失效，请重新登入",$ionicPopup);
          }else if(response.resultCode==0){
            nextPage++
            if (response.datas.length < ENV.rows) {
              hasNextPage = false;
            }
            ordersData = portalsData.concat(response.datas);
            orders = {
              'nextPage': nextPage,
              'hasNextPage': hasNextPage,
              'data': ordersData
            };
            $rootScope.$broadcast('OrderList.OrdersUpdated');
          }
        });
      },
      //getOrderList: function (key) {
      //  var hasNextPage = true;   //是否有下一页
      //  resource_order.save({
      //    key:key,//搜索关键字
      //    page:1,//必填
      //    rows:ENV.rows,//必填
      //    token:ENV.token
      //  }, function (response) {
      //    console.log(response);
      //    if(response.resultCode==10013){
      //      DpDataBase.delTable();
      //      printErrorInfoAndReturnLogin("token失效，请重新登入",$ionicPopup);
      //    }else if(response.resultCode==0){
      //      if (response.datas.length < ENV.rows) {
      //        hasNextPage = false;
      //      }
      //      orders = {
      //        'nextPage': 2,
      //        'hasNextPage': hasNextPage,
      //        'data': response.datas
      //      };
      //      $rootScope.$broadcast('OrderList.OrdersUpdated');
      //    }
      //  });
      //},
      getMoreOrderList: function (key) {
        var nextPage = orders.nextPage;
        var hasNextPage = orders.hasNextPage;
        var portalsData = orders.data;
        resource_order.save({
          key:key,//搜索关键字
          page:nextPage,//必填
          rows:ENV.rows,//必填
          token:ENV.token
        }, function (response) {
          console.log(response);
          if(response.resultCode==10013){
            DpDataBase.delTable();
            //setTimeout(function () {
            printErrorInfoAndReturnLogin("token失效，请重新登入",$ionicPopup);
            //},1000);

          }else if(response.resultCode==0){
            nextPage++;
            if (response.datas.length < ENV.rows) {
              hasNextPage = false;
            }
            ordersData = portalsData.concat(response.datas);
            orders = {
              'nextPage': nextPage,
              'hasNextPage': hasNextPage,
              'data': ordersData
            };
            $rootScope.$broadcast('OrderList.OrdersUpdated');
          }
        });
      },

      hasNextPage: function() {
        if (orders === undefined) {
          return false;
        }
        return orders.hasNextPage;
      }
    }
    function printErrorInfo(error,$ionicPopup){
     $ionicPopup.alert({
        title: '提示',
        template: error,
        okText:'确定',
        cssClass: 'dp-alert'
      });
    }
    function printErrorInfoAndReturnLogin(error,$ionicPopup){
      var alertPopup = $ionicPopup.alert({
        title: '提示',
        template: error,
        okText:'确定',
        cssClass: 'dp-alert'
      });
      alertPopup.then(function(res) {
        console.log('Thank you for not eating my delicious ice cream cone');
        $state.go('login');
      });
    }
  })
  .factory('DpDataBase',function($rootScope){
    var database =window.openDatabase("dpDispatch", "1.1", "DpDB", 102400);
    var userToken;
    return{
      createTable: function () {
        database.transaction(function(tx){
          tx.executeSql('CREATE TABLE IF NOT EXISTS tb_user (id int PRIMARY KEY,user_token VARCHAR(255))');
          console.log("创建地区表");
        },function(err){
          console.log("创建表执行失败"+err);
        },function(){
          console.log("创建表执行成功!");
        });
      },
      insertTable:function(token){
        database.transaction(function(tx){
          tx.executeSql('INSERT INTO tb_user VALUES(?,?)',[1,token],function(tx,resultset){
            if(resultset.rowsAffected) {
              console.log("用户插入数据对表有影响!");
            }
          },function(err){
            console.log("用户插入数据失败:"+err.code);
          });
        },function(err){
          console.log("用户执行失败"+err.code);
        },function(){
          console.log("用户执行成功!");
        })
      },
      queryTable:function(){
        database.transaction(function(tx){
          tx.executeSql('SELECT * from tb_user',[],function(tx,resultset){
            if(resultset.rowsAffected) {
              console.log("插入数据对表有影响!");
            }
            console.log("rowsAffected:" + resultset.rowsAffected);
            console.log("rows:" + resultset.rows.length);
            for(var i = 0; i <  resultset.rows.length;i++){
              userToken=resultset.rows.item(i).user_token;
              console.log(userToken+"+++++++++");
            }
            $rootScope.$broadcast('queryToken');
          },function(err){
            userToken='';
            console.log("插入数据失败:"+err.code);
            $rootScope.$broadcast('queryToken');
          });
        },function(err){
          console.log("执行失败"+err.code);
        },function(){
          console.log("执行成功!");
        })
      },
      getUserToken: function () {
        return userToken;
      },
      delTable:function(){
        database.transaction(function(tx){
          tx.executeSql('delete from tb_user where id = ?',[1],function(tx,resultset){
            if(resultset.rowsAffected) {
              console.log("用户删除数据对表有影响!");
            }
            $rootScope.$broadcast("delTable");
          },function(err){
            console.log("用户删除数据失败:"+err.code);
          });
        },function(err){
          console.log("用户执行失败"+err.code);
        },function(){
          console.log("用户执行成功!");
        })
      },
    }
  })
  .factory('fileReader', ["$q", "$log", function($q, $log){
    var onLoad = function(reader, deferred, scope) {
      return function () {
        scope.$apply(function () {
          deferred.resolve(reader.result);
        });
      };
    };

    var onError = function (reader, deferred, scope) {
      return function () {
        scope.$apply(function () {
          deferred.reject(reader.result);
        });
      };
    };

    var getReader = function(deferred, scope) {
      var reader = new FileReader();
      reader.onload = onLoad(reader, deferred, scope);
      reader.onerror = onError(reader, deferred, scope);
      return reader;
    };

    var readAsDataURL = function (file, scope) {
      var deferred = $q.defer();
      var reader = getReader(deferred, scope);
      reader.readAsDataURL(file);
      return deferred.promise;
    };

    return {
      readAsDataUrl: readAsDataURL
    };
  }]);
